package com.exam.controller;

import com.exam.entity.Student;
import com.exam.service.StudentService;
import com.exam.util.FileUtils;
import com.exam.util.ZLConstants;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
public class StudentController {

    @Resource
    private StudentService studentService;

    @RequestMapping("/student")
    public Object studentManagement(String op, String sbirth, String semail, String stel, String sunivsersity, MultipartFile savator, HttpSession session, HttpServletRequest request){
        if(op!=null && !"".equals(op)){
            if("all".equals(op)){
                List<Map<String,Object>> stus = studentService.getAllStudents();
                return stus;
            }else if("saveInfo".equals(op)){
                Student stu = (Student) session.getAttribute(ZLConstants.USER);
                stu.setSbirth(sbirth);
                stu.setSemail(semail);
                stu.setStel(stel);
                stu.setSunivsersity(sunivsersity);
                stu.setSavator("/image/"+savator.getOriginalFilename());
                int res = studentService.saveInfo(stu);
                if(res>=1){
                    //保存头像
                    FileUtils.saveFile(savator,request);
                    //刷新session中的User对象
                    session.setAttribute(ZLConstants.USER, stu);
                }
                return res;
            }
        }
        return null;
    }

    @GetMapping("checkStuNo")
    public Object checkStuNo(String no){
        Student student = studentService.getBySno(no);
        return student==null? 0 : 1 ;
    }

    public void setStudentService(StudentService studentService) {
        this.studentService = studentService;
    }
}
